package d1_midterm_examination.demo05;

public class Test {
    public static void main(String[] args) {
        //目标: 二分查找的应用
        int[] nums = {5, 7, 7, 7, 7, 8, 8, 9, 10};
//        int leftIndex = getLeftIndex(nums, 7);
        System.out.println(getLeftIndex(nums, 7));
        System.out.println(getRightIndex(nums, 7));
        System.out.println("[" + getLeftAndRightIndex(nums, 7, true) +"," +getLeftAndRightIndex(nums, 7, false)+ "]");
    }


    private static int getLeftAndRightIndex(int[] nums, int target, boolean flag) {
        //1.定义开始索引
        int start = 0;
        //2.定义末尾索引
        int end = nums.length - 1;
        //6.定义一个变量,用于记录是否找到目标数值
        int result = -1; //假设不存在
        //4.开始查找
        while (start <= end) {
            //3.定义中间值索引
            int middle = (start + end) / 2;//定义在里面,中间值才会变
            //5.开始做判断
            if (target > nums[middle]) {
                start = middle + 1;
            } else if (target < nums[middle]) {
                end = middle - 1;
            } else {
                result = middle;
                //true 代表 向左找
                //false 代表 向右找
//                flag ? start = middle - 1 :   end = middle + 1;
                if (flag) {
                    end = middle - 1;
                } else {
                    start = middle + 1;
                }

            }
        }

        return result;
    }



    /**
     * 找到第一个值之后开始往,左边找
     *
     * @param nums
     * @param target
     * @return
     */
    private static int getLeftIndex(int[] nums, int target) {
        //1.定义开始索引
        int start = 0;
        //2.定义末尾索引
        int end = nums.length - 1;
        //6.定义一个变量,用于记录是否找到目标数值
        int result = -1; //假设不存在
        //4.开始查找
        while (start <= end) {
            //3.定义中间值索引
            int middle = (start + end) / 2;//定义在里面,中间值才会变
            //5.开始做判断
            if (target > nums[middle]) {
                start = middle + 1;
            } else if (target < nums[middle]) {
                end = middle - 1;
            } else {
                result = middle;
                end = middle - 1;
            }
        }

        return result;
    }

    /**
     * 找到中间值后,开始往右边找
     * @param nums
     * @param target
     * @return
     */
    private static int getRightIndex(int[] nums, int target) {
        //1.定义开始索引
        int start = 0;
        //2.定义末尾索引
        int end = nums.length - 1;
        //6.定义一个变量,用于记录是否找到目标数值
        int result = -1; //假设不存在
        //4.开始查找
        while (start <= end) {
            //3.定义中间值索引
            int middle = (start + end) / 2;//定义在里面,中间值才会变
            //5.开始做判断
            if (target > nums[middle]) {
                start = middle + 1;
            } else if (target < nums[middle]) {
                end = middle - 1;
            } else {
                result = middle;
                start = middle + 1;
            }
        }

        return result;
    }
}
